package com.xiaohong.oauth.controller;


import com.xiaohong.oauth.service.UserLoginService;
import com.xiaohong.user.feign.ChatUserFeign;
import com.xiaohong.user.pojo.User;
import entity.Result;
import entity.StatusCode;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.HttpClientErrorException;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserLoginController {

    //客户端id
    @Value("${auth.clientId}")
    private String clientId;

    //客户端密钥
    @Value("${auth.clientSecret}")
    private String clientSecret;

    @Autowired
    private UserLoginService userLoginService;

    @Autowired
    private ChatUserFeign chatUserFeign;

    /**
     * 参数传递:
     * 1.账号 username=xiaohong
     * 2.密码 password=xiaohong
     * 3.授权方式 grant_type=password
     * 请求头传递
     * 4. Basic Base64(客户端ID:客户端秘钥) Authorization=Basic Y2hhbmdnb3U6Y2hhbmdnb3U=
     */
    @PostMapping("/login")
    public Result login(@RequestBody User user, HttpServletRequest request) throws Exception {

        //获取用户登录IP地址
        String ip = request.getRemoteAddr();

        // 判断用户是否存在
        User iUser = new User();
        iUser.setUsername(user.getUsername());
        List<User> data = chatUserFeign.findList(iUser).getData();
        if (data == null || data.size() == 0){
            return new Result(true, StatusCode.PARAMETERERROR,"用户不存在！");
        }


//        if (loginUser.getAgree() != null && !loginUser.getAgree()){
//            return new Result(false, StatusCode.PARAMETERERROR,"登录失败,未勾选用户协议和隐私条款！");
//        }
        String grant_type = "password";
        try {
            ResponseEntity<Map> entity = userLoginService.login(user.getUsername(), user.getPassword(), grant_type, clientId, clientSecret);
            if (entity.getBody() != null){
                // 更新用户授权Ip
                User fUser = new User();
                fUser.setUsername(user.getUsername());
                User findUser = chatUserFeign.findList(fUser).getData().get(0);
                String authenticatedIP = findUser.getAuthenticatedIP();
                if (!StringUtils.isEmpty(authenticatedIP)){
                    // 检索受信任IP是否有当前IP
                    String[] split = authenticatedIP.split(",");
                    // 数组转List
                    ArrayList< String> arrayList = new ArrayList<String>(split.length);
                    Collections.addAll(arrayList, split);
                    if (arrayList.contains(ip)){
                        // 当前IP为受信任IP
                        return new Result(true, StatusCode.OK,"登录成功！",entity.getBody());
                    }else {
                        // 当前IP为不受信任IP
//                        return new Result(true, StatusCode.OK,"当前设备需验证！");
                        authenticatedIP = "," + ip;
                        findUser.setAuthenticatedIP(authenticatedIP);
                        chatUserFeign.update(findUser);
                        return new Result(true, StatusCode.OK, "登录成功！", entity.getBody());
                    }
                }else {
                    // 将当前IP添加进去受信任IP
                    findUser.setAuthenticatedIP(ip);
                    chatUserFeign.update(findUser);
                    return new Result(true, StatusCode.OK,"登录成功！",entity.getBody());
                }
            }
            return new Result(false, StatusCode.LOGINERROR,"登录失败！",entity.getBody());
        }catch (NullPointerException ne){
            return new Result(true, StatusCode.UNSTART,"服务未启动！");
        }catch (HttpClientErrorException.BadRequest badRequest){
//            return new Result(true, StatusCode.PARAMETERERROR,"用户名或密码错误！");
            return new Result(true, StatusCode.PARAMETERERROR,badRequest.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            return new Result(true, StatusCode.PARAMETERERROR,"服务器内部错误！");
        }
    }

    // 这里的刷新令牌失效时间是数据库里的时间，一旦过了就不能用了，每次刷新获取的刷新令牌失效时间不会重新刷新
    @GetMapping("/refresh")
    public Result refresh(@RequestParam("refresh_token") String refresh_token) throws Exception {
        String grant_type = "refresh_token";
        try {
            ResponseEntity<Map> entity = userLoginService.refresh( grant_type, refresh_token,clientId,clientSecret);
            if (entity.getBody() != null){
                return new Result(true, StatusCode.OK,"刷新令牌成功！",entity);
            }
            return new Result(false, StatusCode.LOGINERROR,"刷新令牌失败！",entity);
        }catch (NullPointerException ne){
            return new Result(true, StatusCode.REPERROR,"服务未启动！");
        }catch (HttpClientErrorException he){
            return new Result(true, StatusCode.REPERROR,"刷新令牌已失效！");
        }
    }

}
